<?php
/**
 * Copyright (c) 2017. Lorem ipsum dolor sit amet, consectetur adipiscing elit.
 * Morbi non lorem porttitor neque feugiat blandit. Ut vitae ipsum eget quam lacinia accumsan.
 * Etiam sed turpis ac ipsum condimentum fringilla. Maecenas magna.
 * Proin dapibus sapien vel ante. Aliquam erat volutpat. Pellentesque sagittis ligula eget metus.
 * Vestibulum commodo. Ut rhoncus gravida arcu.
 */

/*
*yf Echa
*2016年8月13日下午2:59:03
*AdController
*/
namespace SDXApi\Controller;
use SDXApi\Common\Tools\AppVersion;
use SDXApi\Listeners\BuyNumberListener;
use SDXApi\Repositories\BuyNowGoodsRepository;
use SDXApi\Service\OrderDistributionTimeService;
use SDXApi\Service\PromoteService;
use SDXApi\Service\QueueService;
use SDXApi\Service\Kingdee\KingdeeService;
use Think\Model;
use Think\Log;
use SDXApi\Service\UserBehavior;
use Com\Gkshipping\GkshippingSubmit;
class StatementController extends AppController {
     
    public function _initialize(){
        parent::_initialize($apptoken, $apptime,true); // TODO: Change the autogenerated stub
    }

    public function show_freight_desc($order_weight=0,$goods_amount){
        if(empty($order_weight)){
            return 0;
        }
        //$order_weight = ceil($order_weight);    //向上取整重量
        if($goods_amount<68){
            //68
            if($order_weight>5){
                $beyond = number_format($order_weight-5,3);
            }
        }else{
            //68元以上
            if($order_weight>10){
                $beyond = number_format($order_weight-10,3);
            }
        }
        return $beyond;
    }

    public function calc_weight($goods_list=0){
        $order_weight = 0;
        //dump($goods_list);
        foreach ($goods_list as $value){
            $order_weight +=$value['goods_number']*$value['goods_weight'];
        }

        //$order_weight = $order_weight;    //向上取整重量
        return $order_weight;
    }
    /**
     * 计算运费
     * @param int $order_weight kg
     * @param int $goods_amount kg
     * @param boolean $get_fast_fee kg
     * @return int
     */
    public function calc_freight($order_weight=0,$goods_amount=0,$get_fast_fee = false){

        $where_activity['start_date'] = array("lt",time());
        $where_activity['end_date'] = array("gt",time());
        $where_activity['status'] = 1;

        $shipping_activity = M("shipping_fee_activity")->where($where_activity)->order("id desc")->find();

        if($shipping_activity){
            $where['user_id'] = I("post.uid");
            $where['add_time'] = array(
                array('gt',strtotime(date("y-m-d",time())." 00:00:00")-28800),
                array('lt',strtotime(date("y-m-d",time())." 23:59:59")-28800)
            );
            $where['order_status'] = array("neq",2);
            $where['shipping_id'] = 3;

            $order_num = M("order_info")->where($where)->count("order_id");
//            dump($order_num);
//            exit();
            $activity_list = M("shipping_fee_activity_detailed")->
            where(array("activity_id"=>$shipping_activity['id']))->select();

            if($activity_list){
                // 取得列的列表
                foreach ($activity_list as $key => $row) {
                    $volume[$key]  = $row['order_num'];
                }
                array_multisort($volume, SORT_DESC);

                foreach ($activity_list as $key=>$value){
                    if($value['order_num']<=$order_num){
                        unset($activity_list[$key]);
                    }
                }
                $activity_info =  reset($activity_list);
            }
        }

        if($get_fast_fee){
            if(empty($activity_info)){
                return 68;
            }else{
                return $activity_info['shipping_fee'];
            }
        }

        if(empty($activity_info)){
            $activity_info['shipping_fee'] = 68;        //免运费价位线
            $activity_info['shipping_first'] = 10;                   //未免运费时 首重价格
            $activity_info['shipping_first_weight'] = 5;            //未免运费时 首重重量
            $activity_info['shipping_first_weight_calc'] = 1;        //未免运费时 续重价格
            $activity_info['shipping_first_weight_unit'] = 0.5;      //未免运费时 续重单位
            $activity_info['shipping_fee_weight'] = 10;           //免运费时 首重重量
            $activity_info['shipping_fee_weight_calc'] = 10;      //免运费时 续重价格
            $activity_info['shipping_fee_weight_unit'] = 10;      //免运费时 续重单位
            $activity_info['order_num'] = 0;
        }
        $beyond_weight = 0;
        if($goods_amount<$activity_info['shipping_fee']){
            //<68	<=5kg	10元
            //      >5kg	10元+X（每增加500g加收1元，超出部分不足500g按500g计算）

            if($order_weight<=$activity_info['shipping_first_weight']){
                $order_freight = $activity_info['shipping_first'];
            }else{
                $order_freight = $activity_info['shipping_first']+
                    ceil(($order_weight-$activity_info['shipping_first_weight'])
                        /$activity_info['shipping_first_weight_unit'])*
                    $activity_info['shipping_first_weight_calc'];
                $beyond_weight = $order_weight-$activity_info['shipping_first_weight'];
            }

            $activity_info['shipping_fee_fast'] = $activity_info['shipping_first'];
        }else{
            //≥68	≤10kg	0元
            //      >10kg	每增加10kg(不满10Kg按10Kg计算)加收10元物流运费

            $activity_info['shipping_fee_fast'] =0; //首重费用

            if($order_weight<=$activity_info['shipping_fee_weight']){
                $order_freight = 0;
            }else{

//                dump($activity_info['shipping_fee_weight']);
//                dump($activity_info['shipping_fee_weight_unit']);
//                dump($activity_info['shipping_fee_weight_calc']);
//                exit();
                $beyond_weight = $order_weight-$activity_info['shipping_fee_weight'];
                $order_freight = ceil(($order_weight-$activity_info['shipping_fee_weight'])
                        /$activity_info['shipping_fee_weight_unit'])*$activity_info['shipping_fee_weight_calc'];
            }
        }

        $data['order_freight'] = $order_freight;                //订单重量
        $data['shipping_fee'] = $activity_info['shipping_fee']; //运费价格
        $data['shipping_fee_fast'] = $activity_info['shipping_fee_fast']; //运费价格 [ 首重 ]
        $data['is_activity'] = $activity_info['order_num'];     //是否时活动
        $data['beyond_weight'] = number_format($beyond_weight,3);   //超出重量
        return $data;
}

    //获取负卖配送时间
    public function get_negative_to_sell_time($cart_goods){
        $now=date("Y-m-d H:i:s");
        $distribution_start_time_for_negative_to_sell='24:00';
        $distribution_start_time_for_negative_to_sell_id=NULL;
        foreach($cart_goods as $goods){
            if($goods['practical_num']-C('rest_goods_number')-$goods['online_safe_inventory']<=0 && $goods['is_negative_to_sell']==1 && $goods['negative_to_sell_start_time']<=$now && $goods['negative_to_sell_end_time']>=$now){
                if($goods['negative_to_sell_deliverytime_start_time'] && strtotime($goods['negative_to_sell_deliverytime_start_time'])<strtotime($distribution_start_time_for_negative_to_sell)){
                    $distribution_start_time_for_negative_to_sell=$goods['negative_to_sell_deliverytime_start_time'];
                    $distribution_start_time_for_negative_to_sell_id=date("H:i",strtotime($goods['negative_to_sell_deliverytime_start_time'])).'#'.date("H:i",strtotime($goods['negative_to_sell_deliverytime_end_time']));
                }
            }
        }

        return $distribution_start_time_for_negative_to_sell_id;
    }


    /*
     * todo 立即结算（订单确认）
     * */
    public function  immediate_settlement(){
        //S('warehouse_deliver_region_data',null);
        $uid=$this->uid;
        $address_id=I('post.address_id');
        $flow_type=I('post.flow_type');
        $rec_ids=I('post.rec_ids');
        $wid = I('post.wid');
        $bonus_id = I('post.bonus_id');
        $show_all_bouns = I('post.show_all_bouns');
        $shopping_type = I('post.shopping_type',0);
        $is_store = I('post.is_store',0);
        global $is_cashier;
        global $cashier_id;
        $is_cashier=I("post.store",0,"int");
        $cashier_id='';
        if($is_cashier==1){
            $cashier_id=I("post.cashier_id");
        }
        $delivery_time_for_negative_to_sell=0;


        /* 取得购物类型 */
        $flow_type = isset($flow_type) ? intval($flow_type) : CART_GENERAL_GOODS;
        $_SESSION ['flow_type']=$flow_type;
        /* 团购标志 */
        if ($flow_type == CART_GROUP_BUY_GOODS) {
            // $this->assign('is_group_buy', 1);
        } /* 积分兑换商品 */ elseif ($flow_type == CART_EXCHANGE_GOODS) {
            //$this->assign('is_exchange_goods', 1);
        } else {
            // 正常购物流程 清空其他购物流程情况
            $_SESSION ['flow_order'] ['extension_code'] = '';
        }

        if($is_store == 1){
            $cart_goods = D('NewCart')->get_redis_goods_by_uid($uid,$wid);
        }else{
            $cart_goods = D('NewCart')->get_cart_goods_by_uid($uid,$wid,$rec_ids,$flow_type);
            if($is_cashier==1){
                $address_id=0;
                $consignee=array();
            }else{
                /**
                 * 收获地址处理
                 */
                if(!is_numeric($address_id)){
                    returnApiError('请输入收货地址');
                }

                // 获取收货人信息
                $consignee = D('Useraddress')->get_address_dafult($uid,$address_id);
                //dump($consignee);
                //exit();
                if(empty($consignee)){
                    returnApiError('请先选择收货地址');
                }
            }

            $_SESSION ['flow_consignee'] = $consignee;

            if(!empty($rec_ids)){  //购物车ID
                $str=substr($rec_ids, -1);
                if($str==','){
                    $rec_ids=substr($rec_ids,0,strlen($rec_ids)-1);
                }
            }

            $delivery_time_for_negative_to_sell=$this->get_negative_to_sell_time($cart_goods);
            if($delivery_time_for_negative_to_sell){
                S('u'.$uid.'_delivery_time_for_negative_to_sell',$delivery_time_for_negative_to_sell,60);
            }

            $get_fac = D('Useraddress')->check_serve_by_address_id($address_id);
        }



        $cart_goods=D('NewCart')->reset_goods_k3_inventory($wid,$cart_goods);
        if(empty($cart_goods)){
            returnApiError('购物车无数据');
        }

        /* 判断是否限购 */
//        $buyNumberListener = new BuyNumberListener();
//        $status = $buyNumberListener->getForeachGoodsIdStatus($cart_goods, $uid);

//        if ($status) {
//            returnApiError($status);
//        }        

        // 取得优惠活动
        if(empty($is_store)){
            $favourable_list = D('NewCart')->favourable_list_flow($uid,$wid);
        }else{
            $favourable_list = D('NewCart')->favourable_list_store_flow($uid,$wid);
        }

        //判断是否有优惠活动已过期
        $existed = D('NewCart')->is_exit_activity($cart_goods,$favourable_list);
        if(!$existed){
            returnApiError('优惠活动已过期，请刷新');
        }

        //处理购物车中的商品活动数据
        $cart_goods_list = D('NewCart')->convert_cart_goods($cart_goods, $favourable_list,false);
//        echo json_encode($cart_goods_list);
//        exit();
        $goods_list_weight = $cart_goods_list;
        //计算购物车金额以及优惠
        $cart_goods_list = D('NewCart')->get_cart_total($cart_goods_list,$favourable_list,$uid,false,$bonus_id);
        if(!empty($cart_goods_list ['goods_outstock_list']) && count($cart_goods_list ['goods_outstock_list'])>0){
            $res['goods_outstock_list'] =  $cart_goods_list ['goods_outstock_list'];
            $goods_name = array();
            foreach ($cart_goods_list ['goods_outstock_list'] as $out_key=>$out_goods){
                $goods_name[] = $out_goods['goods_name'];
            }
            $goods_name_str = implode(',',$goods_name);
            returnApiError('购物车内商品（'.$goods_name_str.'）库存已发生变化，请重新提交订单',$res);
        }
        //检查购物车中的商品价格是否有变动
        if(empty($is_store)){
            D('NewCart')->check_goods_price($cart_goods, $uid);
        }

        //检测是抢购活动商品是否还存在
        $this->check_cart_order_quota($cart_goods,$uid);

		// 取得订单信息
		$order = array (
				'user_id' => $uid,
				'extension_code' => '',
				'pack_id' => 0,
				'card_id' => 0,
				'bonus' => 0,
				'integral' => 0,
				'surplus'=>0
        );
        /* 计算折扣 */
        $discount = $cart_goods_list['total']['discount'];


        $total = $cart_goods_list['total'];

        //如果购物车总额为0时不可提交订单
        if(floatval($total)==0){
            returnApiError('当前购物车商品总额为0，不可提交订单，请选购商品！');
        }
        //获得购物车中商品的总重量、总价格、总数量
        $cart_weight_price = D('Cart')->cart_weight_price($uid,$flow_type);
        $goods_weight_r = $this->calc_weight($goods_list_weight);

        $user_check_bonus = I('post.bonus_id');
        if($user_check_bonus>0){
            //如有红包，则算出红包价格
            $bonus = M('user_bonus as ub')
                ->field('bt.android_version,bt.ios_version,bt.type_money,bt.bonus_discount_type')
                ->join('left join sdx_bonus_type as bt on ub.bonus_type_id=bt.type_id')
                ->where(array("ub.bonus_id"=>$user_check_bonus))
                ->find();

            if (check_app_version($bonus['android_version'], $bonus['ios_version'])) {
                returnApiError('您的APP版本过低，请升级至最新版领取');
            }


            if($bonus['bonus_discount_type']==2){
                $bonus_freight = $total['goods_amount']*(10-$bonus['type_money'])/10;

            }else{
                $bonus_freight = $bonus['type_money'];
            }


        }else{
            $bonus_freight = 0;
        }



        $shipping_fee_info = $this->calc_freight($goods_weight_r,$total['goods_amount']-$bonus_freight);

        $is_use_freight = false;
        $total['is_use_freight'] =  0;  //是否使用运费劵
        if($shipping_fee_info['shipping_fee_fast']>0){
            //已存在首重费，判断是否有免邮券
            //todo 获取运费抵扣劵
            if ($get_fac['is_day']==0&&(!isset($use_bonus) || C('use_bonus') == '1') && ($flow_type != CART_GROUP_BUY_GOODS && $flow_type != CART_EXCHANGE_GOODS)) {
                // 获取运费抵扣劵
                $user_bonus_freight = D('Cart')->user_bonus_freight($this->uid, $get_fac['price'],$total ['cart_total_amount']);


                if (!empty($user_bonus_freight) && count($user_bonus_freight)>0) {
                    //存在运费劵，使用运费券
                    if ($user_bonus_freight[0] ['bonus_id'] > 0) {
                        $bonus = D('NewCart')->bonus_info($user_bonus_freight[0] ['bonus_id'],'',1);    //检查订单红包
                        //dump($user_bonus_freight[0] ['bonus_id']);
                        if (empty($bonus) || $bonus ['user_id'] != $this->uid || $bonus ['order_id'] > 0) {
                            //returnApiError('所选择的红包不存在或者已过期,请重新提交订单');
                        }else{
                            $is_use_freight = true;
                            $total['is_use_freight'] =  1;//是否使用运费劵
                        }
                    }
                }
            }
        }

        if($is_use_freight){
            //已达到免首重费标准，减去首重费
            $shipping_fee_new = $shipping_fee_info['order_freight'] - $shipping_fee_info['shipping_fee_fast'];
        }else{
            $shipping_fee_new = $shipping_fee_info['order_freight'];
        }
        $c_price_start = $shipping_fee_info['shipping_fee'];
        $total['goods_weight'] = $goods_weight_r;    //新的订单总重量
        $total['cart_total_amount'] = number_format($total['goods_amount']+$shipping_fee_new,2, '.', '');    //新的订单总钱数
        if($shopping_type==1){
            $total['order_amount'] = number_format($total['goods_amount']+$shipping_fee_new-$bonus_freight,2, '.', '');    //新的订单总钱数
        }else{
            $total['order_amount'] = number_format($total['goods_amount']-$bonus_freight,2, '.', '');    //新的订单总钱数
        }

        $total['shipping_fee'] = number_format($shipping_fee_new, 2);                            //此单配送钱数
        $c_price = $c_price_start - $total['goods_amount'] + $bonus_freight;
        if($shipping_fee_info['is_activity']>0){
            $is_activity = "满".$c_price_start."元免邮,";
        }else{
            $is_activity = "";
        }
        if($is_use_freight){
            //已达到免首重费标准
            $err_msg = $is_activity."使用免邮券:本单已免首运费";
        }else{
            if($c_price>0){
                $err_msg = $is_activity."还差".number_format($c_price,2)."元";
            }else{
                $err_msg = $is_activity."本单已免首运费";
            }
        }
        if (AppVersion::checkAppName('ios')) {
            $get_fac['price'] = 0;
        }








//        //统计中加入运费模块
//        if($is_use_freight==1){
//            //本单已存在运费劵，不适用运费计算
//            //$total['cart_total_amount'] = $total['cart_total_amount'] - $total['discount'];
//            $total['cart_total_amount'] = number_format($total['goods_amount'],2,  '.', '');    //新的订单总钱数
//            //$total['shipping_fee'] = number_format(5, 2);                                //此单配送钱数
//            $total['shipping_fee'] = number_format(0, 2);                                //此单配送钱数
//            if (AppVersion::checkAppName('ios')) {
//                $get_fac['price'] = 0;
//            }
//        }else{
//            $shipping_fee_info = $this->calc_freight($goods_weight_r,$total['goods_amount']-$bonus_freight);
//            $shipping_fee_new = $shipping_fee_info['order_freight'];
//            $c_price_start = $shipping_fee_info['shipping_fee'];
//            $total['goods_weight'] = $goods_weight_r;    //新的订单总重量
//            $total['cart_total_amount'] = number_format($total['goods_amount']+$shipping_fee_new,2, '.', '');    //新的订单总钱数
//            $total['shipping_fee'] = number_format($shipping_fee_new, 2);                            //此单配送钱数
//            $c_price = $c_price_start - $total['goods_price'] + $bonus_freight;
//            if($shipping_fee_info['is_activity']>0){
//                $is_activity = "运费活动：满 ".$c_price_start." 即可免配送费\n";
//            }else{
//                $is_activity = "";
//            }
//            if($c_price>0){
//                $err_msg = $is_activity."还差".number_format($c_price,2)."元";
//            }else{
//                $err_msg = $is_activity."本单已免首运费";
//            }
//            if (AppVersion::checkAppName('ios')) {
//                $get_fac['price'] = 0;
//            }
//        }



        $shopping_money= sprintf('购物金额小计 %s', $total ['goods_amount_format']);
        $market_price_desc=sprintf('比市场价 %s 节省了 %s (%s)', $total ['formated_market_price'], $total ['formated_saving'], $total ['save_rate']);

        /* 取得可以得到的积分和红包 */
//        $total_integral=D('Cart')->cart_amount(false, $flow_type,$uid) - $total ['bonus'] - $total ['integral_money'];
//        $total_bonus=price_format(D('Cart')->get_total_bonus($uid), false);

        /* 取得配送列表 */
        $region = array(
            $consignee ['country'],
            $consignee ['province'],
            $consignee ['city'],
            $consignee ['district']
        );

        $shipping_list = D('Shipping')->available_shipping_list($region);


        $insure_disabled = true;
        $cod_disabled = true;

        // 查看购物车中是否全为免运费商品，若是则把运费赋为零
        $condition = "`user_id` = '" . $uid . "' AND `extension_code` != 'package_buy' AND `is_shipping` = 0";
        $shipping_count = M('cart')->where($condition)->count();
        foreach ($shipping_list as $key => $val) {

            $shipping_cfg = unserialize_config($val ['configure']);
            $shipping_fee = ($shipping_count == 0 and $cart_weight_price ['free_shipping'] == 1) ? 0 : shipping_fee($val['shipping_code'], unserialize($val ['configure']), $cart_weight_price ['weight'], $cart_weight_price ['amount'], $cart_weight_price ['number']);

            $shipping_list [$key] ['format_shipping_fee'] = price_format($shipping_fee, false);
            $shipping_list [$key] ['shipping_fee'] = $shipping_fee;
            $shipping_list [$key] ['free_money'] = price_format($shipping_cfg ['free_money'], false);
            $shipping_list [$key] ['insure_formated'] = strpos($val ['insure'], '%') === false ? price_format($val ['insure'], false) : $val ['insure'];

            /* 当前的配送方式是否支持保价 */
            if ($val ['shipping_id'] == $order ['shipping_id']) {
                $insure_disabled = ($val ['insure'] == 0);
                $cod_disabled = ($val ['support_cod'] == 0);
            }
            // 兼容过滤ecjia配送方式
            if (substr($val['shipping_code'], 0, 5) == 'ship_') {
                unset($shipping_list[$key]);
            }
            if($val['shipping_code']=="city_express"){
                $shipping_list[$key]['shipping_desc_auto'] = $err_msg;
            	$shipping_list[$key]['shipping_name'] = $val['shipping_name'];
            	$shipping_list[$key]['clock'] = 1;
            	if($err_msg=='订单金额已满足免运费'){
                    $shipping_list[$key]['shipping_ok'] = "0";
                }else{
                    $shipping_list[$key]['shipping_ok'] = "1";
                }

            }else{
                $shipping_list[$key]['shipping_ok'] = "1";
            	$shipping_list[$key]['clock'] = 0;
            }

            //自提方式，获取对应的仓库地址作为自提地址
            if($val['shipping_id']==2){
                $warehouse_info = D('Warehouse')->get_warehouse_address($wid);
                $shipping_list[$key]['shipping_desc'] = $warehouse_info['addr'];
            }
        }

        /* 取得支付列表 */
        if ($order ['shipping_id'] == 0) {
            $cod = true;
            $cod_fee = 0;
        } else {
            $shipping = D('Shipping')->shipping_info($order ['shipping_id']);
            $cod = $shipping ['support_cod'];

            if ($cod) {
                /* 如果是团购，且保证金大于0，不能使用货到付款 */
                if ($flow_type == CART_GROUP_BUY_GOODS) {
                    $group_buy_id = $_SESSION ['extension_id'];
                    if ($group_buy_id <= 0) {
                        returnApiError('error group_buy_id');
                    }
                    $group_buy = D('Goods')->group_buy_info($group_buy_id);
                    if (empty($group_buy)) {
                        returnApiError('group buy not exists: ' . $group_buy_id);
                    }

                    if ($group_buy ['deposit'] > 0) {
                        $cod = false;
                        $cod_fee = 0;

                        /* 赋值保证金 */
                        $gb_deposit=$group_buy ['deposit'];
                    }
                }

                if ($cod) {
                    $shipping_area_info = D('Shipping')->shipping_area_info($order ['shipping_id'], $region);
                    $cod_fee = $shipping_area_info ['pay_fee'];
                }
            } else {
                $cod_fee = 0;
            }
        }

        // 给货到付款的手续费加<span id>，以便改变配送的时候动态显示
        $payment_list = D('Cart')->available_payment_list(1, $cod_fee);
        if (isset($payment_list)) {
            foreach ($payment_list as $key => $payment) {
                // 只保留显示手机版支付方式
                if (!file_exists(ROOT_PATH . 'plugins/payment/' . $payment['pay_code'] . '.php')) {
                    unset($payment_list[$key]);
                }
                if ($payment ['is_cod'] == '1') {
                    $payment_list [$key] ['format_pay_fee'] =$payment ['format_pay_fee'] ;
                }

                /* 如果有易宝神州行支付 如果订单金额大于300 则不显示 */
                if ($payment ['pay_code'] == 'yeepayszx' && $total ['amount'] > 300) {
                    unset($payment_list [$key]);
                }
                /* 如果有余额支付 */
                if ($payment ['pay_code'] == 'balance') {
                    /* 如果未登录，不显示 */
                    if ($this->uid == 0) {
                        unset($payment_list [$key]);
                    } else {
                        if ($_SESSION ['flow_order'] ['pay_id'] == $payment ['pay_id']) {
                            $disable_surplus=1;
                        }
                    }
                }
                // 如果不是微信浏览器访问并且不是微信会员 则不显示微信支付
                if ($payment ['pay_code'] == 'wxpay' && !is_wechat_browser() && empty($_SESSION['openid'])) {
                    unset($payment_list [$key]);
                }
                // 兼容过滤ecjia支付方式
                if (substr($payment['pay_code'], 0, 4) == 'pay_') {
                    unset($payment_list[$key]);
                }
            }
        }

        /* 取得包装与贺卡 */
//        if ($total ['real_goods_count'] > 0) {
//            /* 只有有实体商品,才要判断包装和贺卡 */
//            $use_package = C('use_package');
//            if (!isset($use_package) || C('use_package') == '1') {
//                /* 如果使用包装，取得包装列表及用户选择的包装 */
//                $pack_list=D('Cart')->pack_list();
//            }
//
//            /* 如果使用贺卡，取得贺卡列表及用户选择的贺卡 */
//            $use_card = C('use_card');
//            if (!isset($use_card) || C('use_card') == '1') {
//                $card_list=D('Cart')->card_list();
//            }
//        }

        $user_info = D('Cart')->user_info($this->uid);

        /* 如果使用余额，取得用户余额 */
        $use_surplus = C('use_surplus');
        if ((!isset($use_surplus) || C('use_surplus') == '1') && $this->uid > 0 && $user_info ['user_money'] > 0) {
            // 能使用余额
            $allow_use_surplus=1;
            $your_surplus=$user_info ['user_money'];
        }

        /* 如果使用积分，取得用户可用积分及本订单最多可以使用的积分 */
//        $use_integral = C('use_integral');
//        if ((!isset($use_integral) || C('use_integral') == '1') && $this->uid > 0 && $user_info ['pay_points'] > 0 && ($flow_type != CART_GROUP_BUY_GOODS && $flow_type != CART_EXCHANGE_GOODS)) {
//            // 能使用积分
//            $allow_use_integral=1;
//            $order_max_integral=D('Cart')->flow_available_points($uid);// 可用积分
//            $your_integral=$user_info ['pay_points'];// 用户积分
//        }



        /* 如果使用红包，取得用户可以使用的红包及用户选择的红包 */
        $bonus_list = array();
        $use_bonus = C('use_bonus');
        $allow_use_bonus = 0;
        $can_use_bouns_count = 0;
        if ((!isset($use_bonus) || C('use_bonus') == '1') && ($flow_type != CART_GROUP_BUY_GOODS && $flow_type != CART_EXCHANGE_GOODS)) {
            // 取得用户可用红包
            if(empty($show_all_bouns) && $show_all_bouns!=1){
                $show_all = false;
            }else{
                $show_all = true;
            }

            $date_param = array();
            $best = I('post.best_time','');		//配送时间
            if(!empty($best)){
                $best=explode("-",$best);
                $date_param['best_time'] = $best[1];
                $date_param['best_time_start'] = $best[0];
            }

            $user_bonus = D('Cart')->user_bonus($this->uid, $total ['goods_amount'],$cart_goods,$consignee,$get_fac,$date_param,$show_all,$shopping_type,$wid);
            if (!empty($user_bonus) && count($use_bonus)>0) {
                foreach ($user_bonus as $key => $val) {
                    $user_bonus [$key] ['bonus_money_formated'] = price_format($val ['type_money'], false);
                    if($val['can_use']==1){
                        $can_use_bouns_count++;
                    }
                }
                $bonus_list=$user_bonus;
            }
            $allow_use_bonus=1; // 能使用红包
        }


        /* 如果能开发票，取得发票内容列表 */
//        $can_invoice = C('can_invoice');
//        $invoice_content = C('invoice_content');
//        if ((!isset($can_invoice) || $can_invoice == '1') && isset($invoice_content) && trim($invoice_content) != '' && $flow_type != CART_EXCHANGE_GOODS) {
//            $inv_content_list = explode("\n", str_replace("\r", '', C('invoice_content')));
//           // $this->assign('inv_content_list', $inv_content_list);
//            $inv_type_list = array();
//            $invoice_type = C('invoice_type');
//            foreach ($invoice_type['type'] as $key => $type) {
//                if (!empty($type)) {
//                    $inv_type_list [$type] = $type . ' [' . floatval($invoice_type['rate'] [$key]) . '%]';
//                }
//            }
//
//        }
        $cart_goods_list_group = D('NewCart')->get_cart_goods_list_group($cart_goods_list['goods_list']);

        $shopping_bag_info = $this->get_shopping_bag($uid,$wid);

        $immsettdata=array(
            'consignee'=>$consignee,//获取收货人信息
            'cart_goods'=>$cart_goods_list['goods_list'],//对商品信息赋值
            'discount'=>$discount,//计算折扣
            'favour_list'=>$favourable_list,    //活动列表
            'total'=>$total,//计算订单的费用
            'shopping_money'=>$shopping_money,
            'market_price_desc'=>$market_price_desc,
//            'total_integral'=>$total_integral,//取得可以得到的积分
//            'total_bonus'=>$total_bonus,    //取得可以得到的红包
            'shipping_list'=>$shipping_list,//取得配送列表
            'cart_weight_price'=>$cart_weight_price,//获得购物车中商品的总重量、总价格、总数量
            'shipping_count'=>$shipping_count,//配送数
            'insure_disabled'=>$insure_disabled,//当前的配送方式是否支持保价
            'cod_disabled'=>$cod_disabled,
            'shipping'=>$shipping,
            'shipping_fee'=>$total['shipping_fee'],      //新版需要的配送费
            'gb_deposit'=>$gb_deposit,
            'shipping_area_info'=>$shipping_area_info,
            'payment_list'=>$payment_list,
//            'pack_list'=>$pack_list,
//            'card_list'=>$card_list,
            'user_info'=>$user_info,
            'your_surplus'=>$your_surplus,
            'allow_use_surplus'=>$allow_use_surplus,
//            'allow_use_integral'=>$allow_use_integral,
//            'order_max_integral'=>$order_max_integral,
//            'your_integral'=>$your_integral,
            'bonus_list'=>$bonus_list,
            'allow_use_bonus'=>$allow_use_bonus,
//            'inv_content_list'=>$inv_content_list,
//            'inv_type_list'=>$inv_type_list,
            'order'=>$order,
            'get_fac'=>$get_fac,//根据收货地址计算配送分配费用
            'cart_goods_list_group'=>$cart_goods_list_group,
            'can_use_bouns_count'=>$can_use_bouns_count,
            'shopping_bag_info'=>$shopping_bag_info
        );

        if($immsettdata['get_fac']['price']==99){
            $immsettdata['get_fac']['price'] = 68;
        }

        //添加行为
        $user_bevavior = new UserBehavior();
        $user_bevavior->add_browse($uid, 16);
        $immsettdata['freight_desc'] =
            "1.实付金额小于68元：\n    订单重量不超过5Kg，收取10元运费\n    订单重量超过5Kg，每0.5Kg加收1元（不足0.5Kg 按0.5Kg算）\n2.实付金额大于等于68元：\n    订单重量不超过10Kg，免运费\n    订单重量超过10Kg，每10Kg收10元（不足10Kg 按10Kg算）";
        $immsettdata['freight_desc_array'] = array(
            "实付金额小于68元",
            "订单重量不超过5Kg，收取10元运费",
            "订单重量超过5Kg，每0.5Kg加收1元（不足0.5Kg 按0.5Kg算）",
            "实付金额大于等于68元",
            "订单重量不超过10Kg，免运费",
            "订单重量超过10Kg，每10Kg收10元（不足10Kg 按10Kg算）");
        //获得购物车中商品的总重量、总价格、总数量
        //$cart_weight_price = D('Cart')->cart_weight_price($uid,$flow_type);
        $immsettdata['freight_title'] = "{$goods_weight_r},0,>";//"{$goods_weight_r},{$shipping_fee_info['beyond_weight']},>";
        //发票内容
        $immsettdata['invoice_content'] = D('OrderInvoice')->get_invoice_content();


        //38活动判断订单是否有活动商品 begin
        $this->check_women_day_activity($cart_goods,$uid);

        //38活动判断订单是否有活动商品 end    

        returnApiSuccess($immsettdata);
    }



    /*
     * todo 提交订单
     */
    public function immediate_saveorder(){
        ignore_user_abort(true);

    	if(!IS_POST){
    		returnApiError ( '参数错误' );
    	}

    	$user_id = $this->uid;
    	$hd = I('post.IS_HD');
    	$is_store = I('post.is_store',0);

        $shopping_type = I('post.shopping_type',0);

        //屏蔽用户下单
        if($user_id==80566){
            returnApiError ( '系统出错' );
        }

        if(!empty($user_id)){
            $data = M("blacklist")->where(array('blacklist_type'=>'2','user_id'=>$user_id))->find();
            if($data){
                returnApiError ( '系统出错' );
            }
        }

        global $is_cashier;
        global $cashier_id;
        $is_cashier=I("post.store",0,"int");
        $cashier_id='';
        if($is_cashier==1){
            $cashier_id=I("post.cashier_id");
        }

        $saveorder_uid=S('saveorder_uid_'.$user_id."_".$cashier_id);
        if(!$saveorder_uid){
            S('saveorder_uid_'.$user_id."_".$cashier_id,1,1);
        }else{
            returnApiError('订单正在生成，请稍等！');
        }
        
    	// 处理接收信息
    	$post_data = $this->get_post_data();
        if($is_cashier=='1'){
            $post_data['shipping_id']=4;
            $post_data['referer']='门店';
            $store_wid = I('post.store_wid');
            if ($store_wid == 5) {
                $post_data ['referer'] = '大客户';
            } else if ($store_wid == 8) {
                $post_data ['referer'] = '891';
            }
        }
    	$result = array();
        /* 取得购物类型 */
        $flow_type = isset($_SESSION ['flow_type']) ? intval($_SESSION ['flow_type']) : CART_GENERAL_GOODS;
        /* 检查购物车中是否有商品 */

        /*判读是否线上线下*/
        //todo:备份修改
        if(empty($is_store)){
            $rec_ids = $post_data['rec_ids'];
                if(!empty($rec_ids)){  //购物车ID
                    $str=substr($rec_ids, -1);
                    if($str==','){
                        $rec_ids=substr($rec_ids,0,strlen($rec_ids)-1);
                    }
                }else{
                    returnApiError('没有选择要购买的商品');
                }

                //HD没有填写收货地址的，获取默认的收货地址
                if(empty($post_data['address_id']) && $hd){
                    $default_address=D('Useraddress')->get_address_dafult($user_id);
                    $post_data['address_id'] = $default_address['address_id'];
                }
        }
        //todo:end
        //设置默认时区
        date_default_timezone_set('PRC');


        if($is_store == 1){
            $cart_goods = D('NewCart')->get_redis_goods_by_uid($user_id,$post_data['wid']);
        }else{
            $cart_goods = D('NewCart')->get_cart_goods_by_uid($user_id,$post_data['wid'],$rec_ids,$flow_type);
        }

        $is_free_single = 0;
        $distribution = new OrderDistributionTimeService();

        $get_self = array(2,4);
        if(in_array($post_data['shipping_id'],$get_self)){

//            $post_data['wid']=C('DEFAULT_WID'); //根据配送方式选择到店自提时，指定默认仓库ID
            $change_time = strtotime(date("Y-m-d",time())." 21:30:00");
            if(time()>$change_time){
                $post_data['best_time'] = strtotime(date("Y-m-d",strtotime("+1 day"))." 22:00:00");
                $post_data['best_time_start'] = strtotime(date("Y-m-d",strtotime("+1 day"))." 10:00:00");
            }else{
                $post_data['best_time'] = strtotime(date("Y-m-d",time())." 22:00:00");
                $post_data['best_time_start'] = strtotime(date("Y-m-d",time())." 10:00:00");
            }

            $get_fac['wid'] = $post_data['wid'];
            $get_fac['wdr_id'] = 0;
        }else{

            //todo：备份修改
            //送货上门订单，需验证地址
            if(empty($is_store)){
                // 获取收货人信息
                $consignee = D('Useraddress')->get_consignee($this->uid,$post_data['address_id']);
                if(!in_array($post_data['shipping_id'],$get_self) || !$hd && $is_cashier!=1){
                    /* 检查收货人信息是否完整 */
                    if (!D('Useraddress')->check_consignee_info($consignee, $flow_type)) {
                        /* 如果不完整则转向到收货人信息填写界面 */
                        returnApiError('收货人信息不够完善');
                    }
                }
                if(!$post_data['best_time'] || !$post_data['best_time_start']){
                    returnApiError("请选择配送时间");
                }

                $get_fac = D('Useraddress')->check_serve_by_address_id($post_data['address_id']);	//获取对应的配送区域
                if($get_fac['name']=='-1'){
                    returnApiError("超出配送区域");
                }
                $post_data['wid'] = $get_fac['wid'];
                //验证配送时间是否符合

                if($is_store==0){
                    $delivery_time_for_negative_to_sell=$this->get_negative_to_sell_time($cart_goods);
                    if($delivery_time_for_negative_to_sell){
                        S('u'.$user_id.'_delivery_time_for_negative_to_sell',$delivery_time_for_negative_to_sell,60);
                    }
                }
                

                $dis_time = D("Users")->distributie_time_list_new($get_fac['mode_id'], $get_fac['wdr_id']);

                $is_true_time = false;
                $order_peak = 0;
                foreach ($dis_time['tomorrow'] as $value){
                    if($value['value']==$post_data['best_time_start']."-".$post_data['best_time']){
                        $is_free_single = $value['is_free_single'];  //是否设置超时免单 0-否 1-是
                        $order_peak = $value['order_peak']; //订单峰值
                        $is_true_time = true;
                        break;
                    }
                }
                foreach ($dis_time['today'] as $value){
                    if($value['value']==$post_data['best_time_start']."-".$post_data['best_time']){
                        $is_free_single = $is_free_single ? $is_free_single : $value['is_free_single'];
                        $order_peak = $order_peak ? $order_peak : $value['order_peak'];
                        $is_true_time = true;
                        break;
                    }
                }
                if(!$is_true_time){
                    returnApiError("配送时间已变动，请重新选择");
                }

                //如果设置订单峰值 判断当前时间段是否超额
                if($order_peak){
                    $best_time_order_peak = $distribution->get_best_time_order_peak($get_fac['wdr_id'], $post_data['best_time_start'], $post_data['best_time']);
                    if($best_time_order_peak >= $order_peak){
                        returnApiError("当前配送时间段运力已满，请选择其他时间段！");
                    }
                }
            }
            //todo：end
        }

        if(!$post_data['wid']){
        	returnApiError('找不到对应配送仓库');
        }
        //查询是否为196用户，196用户：仓库id用主仓对应的虚拟仓
        $is_196 = 0;
        $admin_id = 0;
        $user_info = M('users')->field('is_891,196_admin_id')->find($user_id);
        if($user_info['is_891'] == 2){
            $wpid = M('warehouse')->where(array('pid' => $post_data['wid']))->getField('id');
            $post_data['wid'] = $wpid ? $wpid :$post_data['wid'];
            $is_196 = 1;
            $admin_id = $user_info['196_admin_id'];
        }



        $cart_goods=D('NewCart')->reset_goods_k3_inventory($post_data['wid'],$cart_goods);

        if(empty($cart_goods)){
            returnApiError('购物车无数据');
        }

        //38活动判断订单是否有活动商品 begin
        if(in_array($post_data['shipping_id'],$get_self)){
            $check_women_day_res = $this->check_women_day_activity($cart_goods,$user_id);
            if($check_women_day_res['had_activity_goods']){
                $women_day_goods_name = implode(',',$check_women_day_res['goods_list']);
                returnApiError('订单中包含活动商品：'.$women_day_goods_name.',不可选择自提方式');
            }
        }
        //38活动判断订单是否有活动商品 end



        //如果开启队列功能，则进入队列处理
        if(C('ORDER_QUEUE_OPEN')==1){
            $queue_key = 'order_queue';
            $code = 'order_queue_user_'.$user_id;

            $queue_service = new QueueService();
            //加入队列
            $queue_service->add_queue($queue_key,$code);
            //队列等待以及进行队列操作
            $queue_res = $queue_service->check_order_queue($queue_key,$code,$cart_goods,$post_data,$is_store);
            if($queue_res['error']==1){
                returnApiError($queue_res['msg'],$queue_res);
            }
        }
        // 取得优惠活动
        if(empty($is_store)){
            $favourable_list = D('NewCart')->favourable_list_flow($user_id,$post_data['wid']);

        }else{
            $favourable_list = D('NewCart')->favourable_list_store_flow($user_id,$post_data['wid']);
        }

        //判断是否有优惠活动已过期
        $existed = D('NewCart')->is_exit_activity($cart_goods,$favourable_list);
        if(!$existed){
            returnApiError('优惠活动已过期，请刷新');
        }

        //处理购物车中的商品活动数据
        $cart_goods_list = D('NewCart')->convert_cart_goods($cart_goods, $favourable_list,false);

        //计算购物车金额以及优惠
        $cart_goods_list = D('NewCart')->get_cart_total($cart_goods_list,$favourable_list,$user_id,false);

        if(!empty($cart_goods_list ['goods_outstock_list']) && count($cart_goods_list ['goods_outstock_list'])>0){
            $res['goods_outstock_list'] =  $cart_goods_list ['goods_outstock_list'];
            $goods_name = array();
            foreach ($cart_goods_list ['goods_outstock_list'] as $out_key=>$out_goods){
                $goods_name[] = $out_goods['goods_name'];
            }
            $goods_name_str = implode(',',$goods_name);
            returnApiError('购物车内商品（'.$goods_name_str.'）库存已发生变化，请重新提交订单',$res);
        }

        //todo:备份修改
        if(!empty($is_store)){
            //拿到redis数据
            $currentTime = gmtime();
            $redis = cRedis();
            //用户购买的商品以及数量
            $user_key = "cart:".$user_id.":store";
            $user_goods = $redis->hGetAll($user_key);
            $goods_ids = array_keys($user_goods);
            //获取商品的所有信息
            $goods_msg = $redis->hMGet('cart:goods',$goods_ids);
            //转换为php变量
            $errorMsg = '';
            //拿到商品的会员价，促销价，以及促销时间
            $promote = D('NewCart')->getPromotePrice($goods_ids,$post_data['wid']);
            
            for ($x=0;$x<count($goods_ids);$x++){
                $goods_desc = json_decode($goods_msg[$goods_ids[$x]],true);
                $k = array_search($goods_desc['goods_id'],array_column($promote,'goods_id'));
                //判断是否促销价，以及验证价格是否正确
                if($promote[$k]['promote_start_date'] < $currentTime && $promote[$k]['promote_end_date'] > $currentTime){
                    if($goods_desc['promote_price'] != $promote[$k]['promote_price']){
                        $errorMsg .= $goods_desc['goods_name'].'商品价格有变动，';
                        $goods_desc['promote_price'] = $promote[$k]['promote_price'];
                        $goods_desc['goods_price'] = $promote[$k]['promote_price'];
                        $goods_desc['normal_price'] = $promote[$k]['promote_price'];
                        $goods_desc['promote_start_date'] = $promote[$k]['promote_start_date'];
                        $goods_desc['promote_end_date'] = $promote[$k]['promote_end_date'];
                        $goods_desc['giving'] = 4;
                    }
                }else{
                    if($goods_desc['promote_price'] !=0 || $goods_desc['giving'] == 4){
                        $goods_desc['goods_price'] = $promote[$k]['vip_price'];
                        $goods_desc['normal_price'] = $promote[$k]['vip_price'];
                        $goods_desc['promote_price'] = 0;
                        $goods_desc['promote_start_date'] = 0;
                        $goods_desc['promote_end_date'] = 0;
                        $goods_desc['giving'] = 0;
                        $errorMsg .= $goods_desc['goods_name'].'商品价格有变动，';
                    }
                    //验证会员价是否正确
                    if($goods_desc['vip_price'] != $promote[$k]['vip_price']){
                        $errorMsg .= $goods_desc['goods_name'].'商品价格有变动，';
                        $goods_desc['vip_price'] = $promote[$k]['vip_price'];
                        $goods_desc['goods_price'] = $promote[$k]['vip_price'];
                        $goods_desc['normal_price'] = $promote[$k]['vip_price'];
                    }
                }
                //将数据更新到redis中
                $redis->hSet('cart:goods',$goods_ids[$x],json_encode($goods_desc));
            }
            if(!empty($errorMsg)){
                returnApiError($errorMsg."请重新下单");
            }
        }
        //todo:修改完成

        //检查购物车中的商品价格是否有变动
        if(empty($is_store)){
            D('NewCart')->check_goods_price($cart_goods, $user_id);
        }

        //检测是抢购活动商品是否还存在
        $this->check_cart_order_quota($cart_goods,$user_id);

        $post_data['wid'] = $get_fac['wid'];
        // 订单信息
        $order = array(
			'address_id' => $post_data['address_id'],
            'shipping_id' => $post_data['shipping_id'],
            'referer' => $post_data['referer'],
            'pay_id' =>$post_data['pay_id'], // 付款方式
            'pack_id' =>$post_data['pack_id'],
            'card_id' => $post_data['card_id'],
            'card_message' => $post_data['card_message'],
            'surplus' => $post_data['surplus'],
            'integral' => $post_data['integral'],
            'bonus_id' =>$post_data['bonus_id'],
            'need_inv' => $post_data['need_inv'],
            'inv_type' => $post_data['inv_type'],
            'inv_payee' => $post_data['inv_payee'],
            'inv_content' => $post_data['inv_content'],
            'postscript' => $post_data['postscript'],
            'how_oos' => $post_data['how_oos'],
            'need_insure' => $post_data['need_insure'],
            'user_id' => $post_data['user_id'],
            'best_time' => $post_data['best_time'],
            'best_time_start' => $post_data['best_time_start'],
            'best_time_start_initial' => $post_data['best_time_start'],
            'best_time_initial' => $post_data['best_time'],
            'add_time' => gmtime(),
            'order_status' => OS_UNCONFIRMED,
            'shipping_status' => SS_UNSHIPPED,
            'pay_status' => PS_UNPAYED,
            'agency_id' => D('Cart')->get_agency_by_regions(array(
                $consignee ['country'],
                $consignee ['province'],
                $consignee ['city'],
                $consignee ['district']
            )),
            'wid'=>$post_data['wid'],
            'wdr_id'=>$get_fac['wdr_id'],
            'address_tag'=>$consignee['address_tag'],
            '196_admin_id' => $admin_id,
        );

        if(in_array($post_data['shipping_id'],$get_self)){
            $SHOP_INFO = C("SHOP_INFO");
            foreach ($SHOP_INFO as $key_shop=>$value_shop){
                if($value_shop['wid']==$post_data['wid']){
                    $order['longitude'] = $value_shop['longitude'];
                    $order['latitude'] = $value_shop['latitude'];
                }
            }
        }

        /* 扩展信息 */
        if (isset($_SESSION ['flow_type']) && intval($_SESSION ['flow_type']) != CART_GENERAL_GOODS) {
            $order ['extension_code'] = $_SESSION ['extension_code'];
            $order ['extension_id'] = $_SESSION ['extension_id'];
        } else {
            $order ['extension_code'] = '';
            $order ['extension_id'] = 0;
        }

        /* 检查积分余额是否合法 */
        if ($user_id > 0) {

            $user_info = D('Cart')->user_info($user_id);

            $order ['surplus'] = min($order ['surplus'], $user_info ['user_money'] + $user_info ['credit_line']);
            if ($order ['surplus'] < 0) {             $order ['surplus'] = 0;
            }

            // 查询用户有多少积分
//            $flow_points = D('Cart')->flow_available_points($user_id); // 该订单允许使用的积分
//            $user_points = $user_info ['pay_points']; // 用户的积分总数
//
//            $order ['integral'] = min($order ['integral'], $user_points, $flow_points);
//            if ($order ['integral'] < 0) {
//                $order ['integral'] = 0;
//            }
        } else {
            $order ['surplus'] = 0;
            $order ['integral'] = 0;
        }

        $total = $cart_goods_list['total'];

        /* 检查红包是否存在 */
        if ($order ['bonus_id'] > 0) {
            $bonus = D('NewCart')->bonus_info($order ['bonus_id'],'',0);    //检查订单红包
            if (empty($bonus) || $bonus ['user_id'] != $user_id || $bonus ['order_id'] > 0 || $bonus ['min_goods_amount'] > $total ['goods_price'] || $bonus ['shopping_type']!=0 && $bonus ['shopping_type']!=$shopping_type || $bonus ['shopping_type_info']!=0 && !in_array($post_data['wid'],explode(",",$bonus ['shopping_type_info']))) {
//                $order ['bonus_id'] = 0;
                returnApiError('所选择的红包不存在或者已过期,请重新提交订单');
            }
        }

//        /* 检查运费劵是否存在 */
//        if ($order ['bonus_freight_id'] > 0) {
//            $bonus = D('NewCart')->bonus_info($order ['bonus_freight_id'],'',0);    //检查运费红包
//            if (empty($bonus) || $bonus ['user_id'] != $user_id || $bonus ['order_id'] > 0 || $bonus ['min_goods_amount'] > $total ['goods_price']) {
////                $order ['bonus_id'] = 0;
//                returnApiError('所选择的运费劵不存在或者已过期,请重新提交订单');
//            }
//        }
        /* 对商品信息赋值 */
//        $cart_goods = D('Cart')->cart_goods($flow_type,$rec_ids,$user_id); // 取得商品列表，计算合计

        /* 检查商品总额是否达到最低限购金额 */
//        if ($flow_type == CART_GENERAL_GOODS && D('Cart')->cart_amount(true, CART_GENERAL_GOODS,$user_id) < C('min_goods_amount')) {
//            returnApiError('goods_amount_not_enough');
//
//        }

        $is_presell=0;//是否存在预售商品
        $is_negative_to_sell=0;//是否存在负卖商品
        /* 判断是不是实体商品 */
        $dtime=date('Y-m-d',time());
        $dbesttime=date('Y-m-d',$post_data['best_time']);
        $is_morrow=0;//是否次日送达，若是，则1
        if($dtime!=$dbesttime){
            $is_morrow=1;
        }


        foreach ($cart_goods as $key => $val) {
            /* 统计实体商品的个数 */
            if ($val ['is_real']) {
                $is_real_good = 1;
            }

            $now=date("Y-m-d H:i:s");
            if ($val['practical_num'] - C('rest_goods_number')-$val['online_safe_inventory'] >= $val['goods_number']) {
                if ($val['is_auto_morrow_presell'] && $is_morrow) {
                    if ($val['goods_stock'] <= 0) {
                        returnApiError($val['goods_name'] . '库存为0');
                    }elseif($val['goods_stock']-$val['goods_number']<0){
                        returnApiError($val['goods_name'] . '库存为'.$val['goods_stock'].',不足'.$val['goods_number']);
                    }
                    $cart_is_presell['is_presell'] = 1;
                    $is_presell = 1;
                } else {
                    $cart_is_presell['is_presell'] = 0;
                }
            }elseif(isset($val['is_negative_to_sell']) && $val['is_negative_to_sell'] == 1 && $val['negative_to_sell_start_time']<=$now && $val['negative_to_sell_end_time']>=$now){
                $cart_is_presell['is_presell'] = 1;
                $is_presell = 1;
                $is_negative_to_sell=1;
            } else {
                $cart_is_presell['is_presell'] = 1;
                $is_presell = 1;
            }

            $cart_goods[$key]['is_presell'] = $cart_is_presell['is_presell'];
            //            $cart_mod->where(array('rec_id'=>$val['rec_id']))->save($cart_is_presell);
        }

        $order ['is_negative_to_sell']=$is_negative_to_sell;
        if($is_presell){
            $order ['is_presell']=1;
        }else{
            $order ['is_presell']=0;
        }
        if (isset($is_real_good)) {
            $where=array(
              'shipping_id'=>$order ['shipping_id'],
              'enabled'=>1
            );
            $res = M('shipping')->field('shipping_id')->where($where)->find();
            if (!$res) {
                returnApiError('没有此配送方式');
            }
        }

        /* 订单中的总额 */
        if($bonus['bonus_discount_type']==1){
            $total['bonus'] = !empty($bonus['type_money'])?$bonus['type_money']:0;
        }elseif($bonus['bonus_discount_type']==2){
            $total['bonus'] = get_price($total ['goods_price']*((10-$bonus['type_money'])/10));
        }else{
            $total['bonus'] = 0;
        }

        $order ['bonus'] = $total ['bonus'];
        $order ['goods_amount'] = $total ['goods_price'];
        $order ['discount'] = $total ['discount'];



//        不允许提交总金额为0订单
        if ($total['goods_amount'] <= 0) {
            returnApiError('购物车商品总价为零，不可提交！');
        }



        if($post_data['shipping_id']==3){
            /* 收货人信息 */
            foreach ($consignee as $key => $value) {
                $order [$key] = addslashes($value);
            }

            //todo 订单内运费处理
            $goods_weight_r = $this->calc_weight($cart_goods);
            $shipping_fee_info = $this->calc_freight($goods_weight_r,$total['goods_price']-$total['bonus']);


            if($shipping_fee_info['shipping_fee_fast']>0){
                //已存在首重费，判断是否有免邮券
                $user_bonus_freight = D('Cart')->user_bonus_freight($this->uid, $get_fac['price'],$total['goods_amount']);
                if (!empty($user_bonus_freight) && count($user_bonus_freight)>0&&$get_fac['is_day']==0) {
                    //存在运费劵，使用运费券
                    $bonus = D('NewCart')->bonus_info($user_bonus_freight[0]['bonus_id'],'',1);    //检查运费红包
                    if (empty($bonus) || $bonus ['user_id'] != $user_id || $bonus ['order_id'] > 0) {
                        $shipping_fee_new = $shipping_fee_info['order_freight'];
                    }else{
                        $order['bonus_freight_id'] =$user_bonus_freight[0]['bonus_id']; //标记使用此红包
                        $shipping_fee_new = $shipping_fee_info['order_freight']-$shipping_fee_info['shipping_fee_fast'];
                    }
                }else{
                    $shipping_fee_new = $shipping_fee_info['order_freight'];
                }
            }else{
                $shipping_fee_new = $shipping_fee_info['order_freight'];
            }

            $order ['shipping_fee'] = $shipping_fee_new;
            //新增运费模块 并把运费新加到订单总额里面去
            $total['goods_amount'] = $total['goods_amount'] + $shipping_fee_new;  //订单支付金额上加钱
        }else{
            $order ['mobile'] =
                M("users")->where(array("user_id"=>$post_data['user_id']))->getField("mobile_phone");
        }

        $order ['order_amount'] = $this->order_fee_bouns($total['goods_amount'],$order ['bonus']);
        //exit($order ['order_amount']);



        //收银端设置收银人员
        if($is_cashier==1){
            $order ['store_user_id'] = I("post.admin_id",0,"int");
            $order ['paid_amount'] = I("post.paid_amount");
            $order ['change_amount'] = I("post.change_amount");
        }




        /* 配送方式 */
        if ($order ['shipping_id'] > 0) {
            $shipping = D('Shipping')->shipping_info($order ['shipping_id']);
            $order ['shipping_name'] = addslashes($shipping ['shipping_name']);
        }


        $order ['insure_fee'] = !empty($total ['shipping_insure'])?$total ['shipping_insure']:0;    //保价

        /* 支付方式 */
        if ($order ['pay_id'] > 0) {
            $payment = D('Cart')->payment_info($order ['pay_id']);
            $order ['pay_name'] = addslashes($payment ['pay_name']);
        }

        $order ['pay_fee'] = !empty($total ['pay_fee'])?$total ['pay_fee']:0;
        $order ['cod_fee'] = !empty($total ['cod_fee'])?$total ['cod_fee']:0;


        $order ['from_ad'] = !empty($_SESSION ['from_ad']) ? $_SESSION ['from_ad'] : '0';

        $parent_id =M('users')->where(array('user_id'=>$user_id))->getField('parent_id');
        $order ['parent_id'] = $parent_id;

        $order ['best_time'] = $post_data['best_time'];
        $order ['best_time_start'] = $post_data['best_time_start'];

        //自提单，如果需要购物袋，订单中添加
        if($post_data['need_shopping_bag']==1){
            $shopping_bag_info = $this->get_shopping_bag_by_id($post_data['shopping_bag'],$user_id,$post_data['wid']);
            if(!empty($shopping_bag_info['out_stock_goods_list'])){
                returnApiError('购物袋库存不足',$shopping_bag_info['out_stock_goods_list']);
            }else{
                $cart_goods = array_merge($cart_goods,$shopping_bag_info['goods_list']);
                $order = $this->calculate_order_shopping_bag($order,$shopping_bag_info['total_price']);
            }
        }

        /* 插入订单表 */
        $error_no = 0;
        do {
            $order ['order_sn'] = get_order_sn(); // 获取新订单号
            $new_order = D('Cart')->filter_field('order_info', $order);
            $new_order_id = M('order_info')->data($new_order)->add();
            $error_no = M('order_info')->getError();

            if ($error_no > 0 && $error_no != 1062) {
                die($error_no);
            }
        } while ($error_no == 1062); // 如果是订单号重复则重新提交数据
        $order ['order_id'] = $new_order_id;

        D("Users")->get_order_receipt_code($new_order_id);

        /* 插入订单商品 */
        $order_activity_list = $this->add_order_goods($cart_goods, $new_order_id,$cart_goods_list['goods_list']['favourable_goods'],$order['bonus_id']);



        //自提单，没有设置收货地址，不分配仓库
        if(!in_array($post_data['shipping_id'],$get_self) || ($post_data['shipping_id']==2 && $post_data['referer']!='891')){
//        if($post_data['shipping_id']!=2){
            //分配仓库
//            $wid = D('Orderinfo')->auto_updateorder_warehouse($order['user_id'],$order ['order_id'],$post_data['shipping_id'],$order ['address_id'], $is_196);
//            if($wid>0){
//                $post_data['wid'] = $wid;
//            }

            if($is_196){
                //196用户处理仓库
                $wid_196 = M('warehouse')->where(array('pid' => $post_data['wid']))->getField('id');
                $post_data['wid'] = $wid_196 ? $wid_196 : $post_data['wid'];
                $savedata=array(
                    'wid'=> $post_data['wid']);
                $flag = M("order_info")->where(array("order_id"=>$order ['order_id']))->save($savedata);
                if($flag!==false){
                    $order['wid'] = $post_data['wid'];
                }
            }

        }

        //发票处理
        if(I('post.is_invoice') == 1){
            D('OrderInvoice')->add_invoice($new_order_id);
        }


        /* 如果使用库存，且下订单时减库存，如果是预售商品则虚拟库存 */
        if (C('use_storage') == '1' && C('stock_dec_time') == SDT_PLACE) {
        	$pre_storage_res = D('Cart')->change_order_goods_storage($order ['order_id'], true, SDT_PLACE,$order['wid']);
            /*if(!empty($pre_storage_res) && !$pre_storage_res['status']){
                $this->set_order_status($order ['order_id'], 3);	//库存不足，设为无效订单
                returnApiError($pre_storage_res['msg'],$pre_storage_res);
            }*/
        }

        //筛选现售订单商品，进行减相应的实际库存，并且库存相关记录
        $storage_res = $this->save_ordergoods_storage($order ['order_id'], $order['wid'], $user_id);
        if(!empty($storage_res) && !$storage_res['status']){
            $this->set_order_status($order ['order_id'], 3);	//库存不足，设为无效订单
            returnApiError($storage_res['msg'],$storage_res);
        }

        if(in_array($post_data['wid'],C('K3_Wid')) && $new_order_id){

            $kingDee=new KingdeeService();
            $k3SubmitOrder=$kingDee->submitOrderGoodsInventoryRequest($new_order_id,$order,$cart_goods);
            if($k3SubmitOrder['code']==200){
                //$kingDee->autoOrderCancel($new_order_id);
            }else{
                M('order_info')->where('order_id='.$new_order_id)->save(array("order_status"=>2));
                returnApiError('金蝶生成订单出错');
            }

        }

        $Model=new Model();
        /* 限购活动处理 */
        $sql = "INSERT INTO " . C('DB_PREFIX') . "activity_quota(user_id,act_id,order_id,goods_id) " . " SELECT " . $this->uid . ",is_quota,order_id,goods_id FROM " . C('DB_PREFIX') . "order_goods WHERE order_id='$new_order_id' AND is_quota>0 ";
        $Model->execute($sql);

        /* 插入支付日志 */
        $order['log_id'] = D('OrderInfo')->insert_pay_log($new_order_id, $order ['order_amount'], PAY_ORDER);

        /*记录当前支付订单相关活动*/
        if($order['log_id']){
            $this->add_order_activity($order['log_id'],$order_activity_list);
        }

        if ($order ['bonus_id'] > 0) {
            D('Cart')->use_bonus($order['bonus_id'], $new_order_id,$order['log_id']);
        }
        if ($order ['bonus_freight_id'] > 0) {
            //使用运费劵
            D('Cart')->use_bonus($order['bonus_freight_id'], $new_order_id,$order['log_id']);
        }
        /* 清除购物车已下单的商品 */
        //todo:备份修改
        if(empty($is_store)){
            D('Cart')->clear_cart($user_id,$flow_type,$rec_ids);
        }
        //todo:end 2018.4.17

        if($order['order_id']){
        	$result['order_id'] = $order['order_id'];
            $result['order_sn'] = $order['order_sn'];
        	$result['pay_id'] = $order['pay_id'];
            $result['log_id'] = $order['log_id'];
        	$result['rest_pay_time'] = REST_PAY_TIME-(gmtime()-$order['add_time']);
        }

        if($result){
            $this->auto_dispatch_order($order['order_id'],$order);

            //添加到 订单超时免单记录扩展表
            if($is_free_single){
                $distribution->add_order_free_single($order['order_id']);
            }

            //添加当前区域的时间段订单量缓存
            if($order['shipping_id']==3 && $order['196_admin_id']==0){
                $distribution->add_order_best_time_cache($get_fac['wdr_id'], $order['best_time_start'], $order['best_time'], $order['order_id']);
            }


            $data_log['action_note']="所属仓库：".$post_data['wid'];
            $data_log['log_time']=gmtime();
            $data_log['user_id']=$this->uid;
            $data_log['order_id']=$order['order_id'];
            M('order_action')->add($data_log);
            

            //添加到用户行为
            $param = array('isertList', '' , 'submit_order', $order['order_id'], 1);
            \Think\Hook::listen('receng', $param);

            //todo: 备份修改
            if(!empty($is_store)){
                $redis = cRedis();
                $key = "cart:".$user_id.":store";
                $key1 = "cart:cache:".$user_id;
                $wid_key = "cart:wid:".$user_id;
                $gift_key = "cart:gift:".$user_id;
                $bool = $redis->del($key);
                $redis->del($key1);
                $redis->del($wid_key);
                $redis->del($gift_key);
                if(!$bool){
                    returnApiError('购物车商品不存在');
                }
            }
            //todo:end

        	returnApiSuccess($result,'订单生成成功');
        }else{
        	returnApiError('订单生成失败，请重新提交');
        }

    }


    /**
     * 更新极客信息
     * @param $order
     */
    public function update_address_gk($order){

        $city_name=M('region')->where('region_id ='.$order['city'])->getField('region_name');
        $district_name=M('region')->where('region_id ='.$order['district'])->getField('region_name');
        $receiver_address = "广东省广州市".$district_name;
        $receiver_address .= $order['address'];
        if(!empty($order['sign_building'])){
            $receiver_address.= $order['sign_building'];
        }
        if(!empty($order['address_name'])){
            $receiver_address.= $order['address_name'];
        }
        $order_shipping_info = array(
            'city' => $city_name,
            'address' => $receiver_address
        );
        //推送订单
        $Gk_Submit = new GkshippingSubmit();
        $res = $Gk_Submit->check_address($order_shipping_info);
        $area = $res['info']['network_name'];
        $area = str_replace("网点","",$area);
        $this->write_log($order['order_sn'].": ".$receiver_address."--".$area,'jk_address');
        if(!empty($area)){
            M("order_info")->where(array("order_id"=>$order['order_id']))->setField("distribution_company_area",$area);
        }else{
            M("order_info")->where(array("order_id"=>$order['order_id']))->setField("distribution_company_area","未匹配到");
        }

    }
    /**
     * 计算使用红包后的订单金额
     * @param $goods_amount
     * @param $bouns
     * @return int $order_amount
     */
    public function order_fee_bouns($goods_amount,$bouns){
        $order_amount = get_price($goods_amount-$bouns);
        return $order_amount;
    }


    /**
     * 记录支付订单的中活动信息
     * @param $pay_log_id
     * @param $order_activity_list
     */
    public function add_order_activity($pay_log_id,$order_activity_list){
        if(count($order_activity_list)){
            foreach($order_activity_list as $key=>$val){
                $data = array();
                $data['pay_log_id'] = $pay_log_id;
                $data['act_id'] = $val['act_id'];
                $data['discount'] = $val['discount'];
                $data['activity_info'] = serialize($val);
                $data['add_time'] = gmtime();

                M('order_activity')->add($data);
            }
        }
    }

    public function get_post_data(){
    	$data = array();
    	$data['how_oos'] = I('post.how_oos','','addslashes');		//缺货处理方式
    	$data['card_message'] = I('post.card_message',"");		//贺卡内容
    	$data['inv_type'] = I('post.inv_type','');		//发票类型,用户页面选择，取值sdx_shop_config的code字段的值为invoice_type的value',
    	$data['inv_content'] = I('post.inv_content','');			//发票内容
    	$data['inv_payee'] = I('post.inv_payee','');		//发票抬头
    	$best = I('post.best_time','');		//发票抬头

    	$data['postscript'] = I('post.postscript','');		//订单附言
    	$data['shipping_id'] = I('post.shipping_id','');		//用户选择的配送方式id

        if(!empty($best)){
            $best=explode("-",$best);
            $data['best_time'] = $best[1];
            $data['best_time_start'] = $best[0];
        }

    	$data['pay_id'] = I('post.pay_id',0,'int');		//用户选择的支付方式的id
    	$data['pack_id'] = I('post.pack_id',0,'int');		//包装id
    	$data['card_id'] = I('post.card_id',0,'int');		//贺卡id
    	$data['surplus'] = I('post.surplus','0.00','floatval');		//该订单使用余额的数量
    	$data['integral'] = I('post.integral',0,'int');			//使用的积分的数量，取用户使用积分
    	$data['bonus_id'] = I('post.bonus_id',0,'int');		//红包的id
    	$data['need_inv'] = I('post.need_inv',0);			//是否需要发票
    	$data['need_insure'] = I('post.need_insure',0,'int');		//配送是否需要保价
    	$data['user_id'] = $this->uid;			//用户id
    	$data['rec_ids'] = I('post.rec_ids');			//购物车ID。可以为空，为空结算全部购车商品。如果不为空，则传购物车ID，多个用英文逗号','隔开。

    	$data['openid'] =  I('post.openid','');			//微信用户openid
    	$data['address_id'] =  I('post.address_id',0,'int');			//微信用户openid
        $data['wid']=I('post.wid',C('DEFAULT_WID'),'int');
        $data['referer']=I('post.referer','Touch');          //订单来源
        $data['need_shopping_bag'] = I('post.need_shopping_bag');   //是否需要购物袋
        $data['shopping_bag'] = I('post.shopping_bag');
        return $data;
    }


    /**
     * 筛选现售订单商品，进行减相应的实际库存，并且记录
     * @param $order_id
     * @param $wid
     * @param $user_id
     * @return array
     */
    public function save_ordergoods_storage($order_id,$wid,$user_id){
        $ordergoods=D('Orderinfo')->get_ordergoods($order_id,0);//搜现售订单商品，有就减相应的实际库存，并且记录
        $flag = array("status"=>1,"msg"=>"ok",'error_code'=>100);
        if($ordergoods){
            $goodsstorage_list = array();   //商品库存数据集
            $goods_storage = array();   //保存临时库存，解决同一个商品多种优惠情况

            if(in_array($wid,C('K3_Wid'))){
                $goods_sn_list=array();
                foreach ($ordergoods as $g_k=>$g_v){
                    $goods_sn_list[]=$g_v['goods_sn'];
                }
                $kingDee=new KingdeeService();
                $goods_practical_num=$kingDee->getGoodsStockByGoodsSn($wid,$goods_sn_list);
                $goodsstorage_list_k3=$goods_practical_num['data'];
            }
            





            foreach ($ordergoods as $g_k=>$g_v){
                $goodsstorage_stock = D('Goodsstorage')->get_warehous_goods($wid,$g_v['goods_id'],1);

                if(in_array($wid,C('K3_Wid'))) {
                    isset($goodsstorage_list_k3[$g_v["goods_sn"]]) ? $goodsstorage_stock['practical_num'] = $goodsstorage_list_k3[$g_v["goods_sn"]] : $goodsstorage_stock['practical_num'] = 0;
                }
                
                //获取金蝶库存
                if(empty($goodsstorage_stock)){
                    $flag['status'] = 0;
                    $flag['msg'] ="商品".$g_v['goods_name']."库存为0";
                    $flag['error_code'] = 201;
                    return $flag;
                }
                if(!empty($goodsstorage_stock) && empty($goods_storage[$g_v['goods_id']]) && empty($goodsstorage_list[$g_v['goods_id']])){
                    $goodsstorage_list[$g_v['goods_id']] = $goodsstorage_stock;
                    $goods_storage[$g_v['goods_id']] = $goodsstorage_stock['practical_num'];
                }
                if($g_v['goods_number']>$goods_storage[$g_v['goods_id']]){
                    $flag['status'] = 0;
                    $flag['msg'] ="商品".$g_v['goods_name']."库存仅剩".$goods_storage[$g_v['goods_id']]."份";
                    $flag['error_code'] = 201;
                    return $flag;
                }

                $goods_storage[$g_v['goods_id']] = $goods_storage[$g_v['goods_id']] - $g_v['goods_number'];
            }

            if(!in_array($wid,C('K3_Wid'))) {
                $temp_goods_storage = array();  //保存临时库存，解决同一个商品多种优惠情况
                foreach ($ordergoods as $k => $v) {
                    $goodsstorage = $goodsstorage_list[$v['goods_id']];
                    if (!empty($goodsstorage_list[$v['goods_id']]) && empty($temp_goods_storage[$v['goods_id']])) {
                        $temp_goods_storage[$v['goods_id']]['practical_num'] = $goodsstorage['practical_num'];
                        $temp_goods_storage[$v['goods_id']]['freeze_num'] = $goodsstorage['freeze_num'];
                    }
                    if ($goodsstorage) {
                        //减去实际库存
                        $res = D('Goodsstorage')->save_theactual_goods($wid, $v['goods_id'], $v['goods_number']);
                        if ($res!==false) {
                            $goodsrecord = array(
                                'goods_storage_id' => $goodsstorage['id'],
                                'wpid' => 0,
                                'wid' => $goodsstorage['wid'],
                                'goods_id' => $v['goods_id'],
                                'goods_sn' => $v['goods_sn'],
                                'operation_num' => $v['goods_number'],
                                'real_num' => $temp_goods_storage[$v['goods_id']]['practical_num'] - $v['goods_number'],
                                'frozen_num' => 0,
                                'defective_num' => 0,
                                'operation_userid' => 0,
                                'average_userid' => $user_id,
                                'operation_addtime' => gmtime(),
                                'source_no' => $v['order_sn'],
                                'record_type' => 10,
                                'remark' => '商品下单',
                            );
                            //商品出入库记录
                            D('Goodsstoragerecord')->add_storage_record($goodsrecord);

                            $temp_goods_storage[$v['goods_id']]['practical_num'] = $temp_goods_storage[$v['goods_id']]['practical_num'] - $v['goods_number'];

                            $goodsfreezerecord = array(
                                'goods_storage_id' => $goodsstorage['id'],
                                'wid' => $goodsstorage['wid'],
                                'goods_id' => $v['goods_id'],
                                'goods_sn' => $v['goods_sn'],
                                'goods_name' => $v['goods_name'],
                                'freeze_num' => $v['goods_number'],
                                'real_num' => 0,
                                'frozen_num' => $temp_goods_storage[$v['goods_id']]['freeze_num'] + $v['goods_number'],
                                'defective_num' => 0,
                                'operation_userid' => 0,
                                'average_userid' => $user_id,
                                'operation_addtime' => gmtime(),
                                'source_no' => $v['order_sn'],
                                'record_type' => 4,
                                'remark' => '商品下单',
                            );
                            //商品冻结出入记录
                            D('Goodsfreezerecord')->add_freeze_record($goodsfreezerecord);

                            $temp_goods_storage[$v['goods_id']]['freeze_num'] = $temp_goods_storage[$v['goods_id']]['freeze_num'] + $v['goods_number'];
                        } else {
                            $flag['status'] = 0;
                            $flag['msg'] = "商品" . $v['goods_name'] . "仓库库存不足";
                            $flag['error_code'] = 201;
                            return $flag;
                        }
                    } else {
                        $flag['status'] = 0;
                        $flag['msg'] = "商品" . $v['goods_name'] . "仓库库存不足";
                        $flag['error_code'] = 201;
                        return $flag;
                    }
                }
            }
        }
        return $flag;
    }
    
    /**
     * 检查购物车商品是否有价格变动
     */
    private function check_goods_price($cart_goods,$uid){
    	if(count($cart_goods)>0){
    		$cart_goods_list = array();
    		$have_change = false;
    		$msg = '购物车中商品价格有变动';
    		$user_rank = M('users')->where(array("user_id"=>$uid))->getField('user_rank');

    		foreach($cart_goods as $goods){

    			if($goods['is_quota']>0){
    				$res = $this->check_quota_price($goods,$uid,$goods['is_quota']);
    			}
    			elseif($goods['is_gift']>0)
				{
    				$res = $this->check_gift_price($goods,$uid,$goods['is_gift']);
    			}
//    			else if ($goods['giving'] == 4)
//    			{
//					$res = $this->check_promote_price($goods);
//				}
    			else
				{
    				$res = $this->check_normal_price($goods,$uid,$user_rank);
    			}

    			if($res['have_change']==1){
    				$cart_goods_list[] = $res['cart_goods'];
    				$have_change = true;
    			}
    		}

    		if($have_change){
    			returnApiError($msg,$cart_goods_list);
    		}
    	}
    }

	/**
	 * 检测促销价价格变动
	 * Created by Jerry
	 * @param $goods
	 * @return array
	 */
    protected function check_promote_price($goods)
	{
		$promoteService = new PromoteService();
		$promoteRs = $promoteService->isPromote($goods['user_id'], $goods['goods_id'], $goods['goods_number']);

		$data = array(
			'have_change'	=>	'0',
		);
		if ($promoteRs == false && ($goods['goods_price'] == $goods['promote_price'])) {
			returnApiError('购物车促销商品价格有变动');
		}


		return $data;
	}

    /* 插入订单商品 */
    private function add_order_goods(&$cart_goods,$order_id,$favourable_list,$bonus_id=0){
        $order_activity_list = array();
        if($bonus_id){
            $bonus_proportion = D("NewCart")->get_bonus_proportion($cart_goods,$bonus_id);
            $bonus_goods_num=1;
            $bonus_goods_use_amount=0;
        }
        if(!empty($cart_goods)){
            foreach ($cart_goods as $key=>$goods){
                //如果是赠品商品，但是没有购买相关的商品，则不能购买
                $goods_data = array();
                $goods_data['goods_price'] = $goods['goods_price'];
                $goods_data['bonus_price']=0;
                //计算符合条件的商品红包的折扣金额
                if($bonus_id && $goods['use_bonus']==1){
                    $goods_data['bonus_price']=sprintf("%.2f",$goods['goods_price']*(1-$bonus_proportion['bonus_goods_proportion']));
                    if($bonus_proportion['bonus_goods_num']==$bonus_goods_num){
                        $goods_data['bonus_price']=sprintf("%.2f",($bonus_proportion['bonus_money']-$bonus_goods_use_amount)/$goods['goods_number']);
                    }
                    $goods_data['goods_price']=sprintf("%.2f",$goods['goods_price']-$goods_data['bonus_price']);

                    $bonus_goods_use_amount+=$goods_data['bonus_price']*$goods['goods_number'];
                    $bonus_goods_num++;
                }
                $cart_goods[$key]['bonus_price']=$goods_data['bonus_price'];
                $goods_data['order_id'] = $order_id;
                $goods_data['goods_id'] = $goods['goods_id'];
                $goods_data['goods_name'] = $goods['goods_name'];
                $goods_data['goods_sn'] = $goods['goods_sn'];
                $goods_data['product_id'] = $goods['product_id'];
                $goods_data['goods_number'] = $goods['goods_number'];
                $goods_data['market_price'] = $goods['market_price'];
                $goods_data['goods_attr'] = $goods['goods_attr'];
                $goods_data['is_real'] = $goods['is_real'];
                $goods_data['extension_code'] = $goods['extension_code'];
                $goods_data['is_gift'] = $goods['is_gift'];
                $goods_data['parent_id'] = $goods['parent_id'];
                $goods_data['is_quota'] = $goods['is_quota'];
                $goods_data['goods_attr_id'] = $goods['goods_attr_id'];
                $goods_data['is_presell'] = $goods['is_presell'];
                $goods_data['act_id'] = $goods['act_id'];
                $goods_data['expiration_date'] = $goods['expiration_date'];
                $goods_data['cart_discount'] = $goods['goods_discount'];
                $goods_data['k3_supplier_sn'] = isset($goods['k3_supplier_sn'])?$goods['k3_supplier_sn']:"";
                $goods_data['k3_vmi'] = isset($goods['k3_vmi'])?$goods['k3_vmi']:"";
                if($goods['goods_discount']>0){
                    $goods_data['goods_price']=round($goods['goods_price']*($goods['goods_discount']/10),2);
                    $goods_data['cart_discount_price'] = round($goods['goods_price']-$goods_data['goods_price'],2);
                    $cart_goods[$key]['discount_price'] =  (1-$goods_data['goods_discount'])*$goods['goods_price'];
                }
                if($goods['act_id']>0){
                    $favourable_info = $this->get_activityinfo($goods['act_id'],$favourable_list);
                    if($favourable_info['act_type']==FAT_DISCOUNT){
                        
                        $goods_data['goods_discount'] = round($favourable_info['act_type_ext'] / 10,2);
                        $goods_data['discount_price'] = round($goods['goods_price']*$favourable_info['act_type_ext'] / 100,2);
                        $cart_goods[$key]['discount_price'] =  $goods['goods_price']-$goods_data['discount_price'];
                    }
                    if($favourable_info['act_type']==FAT_PRICE){
                        //TODO:
                        $join_goods_arr = explode(',',$favourable_info['act_range_ext']);
                        $amount = 0.00;
                        foreach ($join_goods_arr as $join_goods_value){
                            $act_key = array_search($join_goods_value,array_column($cart_goods,'goods_id'));
                            $amount += $cart_goods[$act_key]['goods_number']*$cart_goods[$act_key]['goods_price'];
                        }

                        $goods_data['goods_discount'] = round(((($goods_data['goods_price']*$goods_data['goods_number'])/$amount)*$favourable_info['act_type_ext'])/$goods_data['goods_number'],2);
                        $cart_goods[$key]['discount_price'] = $goods_data['goods_discount'];
                    }
                    $goods_data['favourable_info'] = serialize($favourable_info);
                }
                $cart_goods[$key]['goods_discount']=$goods_data['goods_discount'];

                $goods_data['giving'] = $goods['giving'];

                /* 插入订单商品 */
                $rec_id = M('order_goods')->add($goods_data);
                //添加订单商品成功，订单加入当前的活动
                if($rec_id && $goods['act_id']>0){
                    $order_activity_list[$goods['act_id']] = $favourable_info;
                }
            }
        }
        return $order_activity_list;
    }
    

    /**
     * 获取其中对应的act_id活动的信息
     * @param $act_id
     * @param $favourable_list
     * @return bool
     */
    private function get_activityinfo($act_id,$favourable_list){
        foreach ($favourable_list as $activity){
            if($act_id!=$activity['info']['act_id']){
                continue;
            }else{
                return $activity['info'];
            }
        }
        return false;
    }



    /*
     * 普通商品购物车价格变动检查
     */
    private function check_normal_price($goods,$uid,$user_rank){
    	$result = array('have_change'=>0);
		$map = array();
		$spec = "";

		if($goods['goods_attr_id']){
			$spec = explode(',', $goods['goods_attr_id']);
		}
		$goods_price = D('Goods')->get_final_price($goods['goods_id'], $goods['goods_number'], true, $spec, $uid);
////		促销价
//		$promote_price = bargain_price($goods['promote_price'], $goods['promote_start_date'], $goods['promote_end_date']);
//		if ($promote_price > 0 && ($goods_price - $goods['promote_price'] != 0)) {
//			returnApiError('促销商品价格和数量有所变动');
//		}



		if ($goods['giving'] > 0) {

			if ($goods['is_buynow'] == 0) {
				$promoteService = new PromoteService();
				$status = $promoteService->getPromotePriceStatus($goods);

				if ($status) {
					$this->isPriceChange($goods, $goods_price);
				}
				else{
					D('cart')->where(array('rec_id'=>$goods['rec_id']))->setField('giving', 0);
				}
			}
			else if($goods['is_buynow'] == 1){
				$buyNowGoodsService = new BuyNowGoodsRepository($uid);
				$status = $buyNowGoodsService->getBuyNowGoodsData($goods);
				if ($status['buy_now_status'] == 3) {
					$this->isPriceChange($goods, $goods_price);
				}
			}
		}


        if(($goods_price - $goods['goods_price']) != 0){
            D('cart')->where(array('rec_id'=>$goods['rec_id']))->setField('goods_price',$goods_price);
            $goods['new_goods_price'] = $goods_price;
            $result['have_change'] = 1;
            $result['cart_goods'] = $goods;
        }

        return $result;
    }

	/**
	 * Created by Jerry
	 * @param $goods
	 * @param $goods_price
	 * @return bool
	 */
    protected function isPriceChange($goods, $goods_price)
	{
		$promote_price = bargain_price($goods['promote_price'], $goods['promote_start_date'], $goods['promote_end_date']);
		if ($promote_price > 0 && ($goods_price - $goods['promote_price'] != 0)) {
			returnApiError('商品价格和数量有所变动');
		}

		return true;
	}
    
    /*
     * 抢购商品购物车价格变动检查
     */
    private function check_quota_price($goods,$uid,$act_id){
    	$result = array('have_change'=>0);
    	$activity = D ( 'favourable_activity' );
    	if(S('favourable_'.$goods['is_quota'])){
    		$favourable = S('favourable_'.$goods['is_quota']);
    	}else{
    		$favourable = $activity->favourable_info($goods['is_quota']);
    		if(!empty($favourable)){
    			S('favourable_'.$goods['is_quota'],$favourable,20);
    		}
    	}
    	if(!empty($favourable['quota'])){
    		$favourable_goods_list = $favourable['quota'];
    		foreach ($favourable_goods_list as $favourable_goods){
    			if($favourable_goods['id']==$goods['goods_id'] && ($favourable_goods['price']-$goods['goods_price']!=0)){
    				$goods_price = $favourable_goods['price'];
    				D('cart')->where(array('rec_id'=>$goods['rec_id']))->setField('goods_price',$goods_price);
    				$goods['new_goods_price'] = $goods_price;
    				$result['have_change'] = 1;
    				$result['cart_goods'] = $goods;
    			}
    		}
    	}
    	
    	return $result;
    }
    
    /*
     * 赠送或优惠商品购物车价格变动检查
     */
    private function check_gift_price($goods,$uid,$act_id){
    	$result = array('have_change'=>0);
    	$activity = D ( 'favourable_activity' );
    	if(S('favourable_'.$goods['is_gift'])){
    		$favourable = S('favourable_'.$goods['is_gift']);
    	}else{
    		$favourable = $activity->favourable_info($goods['is_gift']);
    		if(!empty($favourable)){
    			S('favourable_'.$goods['is_gift'],$favourable,20);
    		}
    	}
    	if(!empty($favourable['gift'])){
    		$favourable_goods_list = $favourable['gift'];
    		foreach ($favourable_goods_list as $favourable_goods){
    			if($favourable_goods['id']==$goods['goods_id'] && ($favourable_goods['price']-$goods['goods_price']!=0)){
    				if($goods['goods_price']==0){
                        M('cart')->where(array('rec_id'=>$goods['rec_id']))->delete();
                    }elseif($favourable_goods['price']==0){
                        M('cart')->where(array('rec_id'=>$goods['rec_id']))->delete();
                    }else{
                        $goods_price = $favourable_goods['price'];
                        M('cart')->where(array('rec_id'=>$goods['rec_id']))->setField('goods_price',$goods_price);
                    }
                    $goods['new_goods_price'] = $goods_price;
                    $result['have_change'] = 1;
                    $result['cart_goods'] = $goods;
    			}
    		}
    	}
    	 
    	return $result;
    }
    
    /*
     * 修改订单状态
     */
    private function set_order_status($order_id,$status){
    	M('order_info')->where(array('order_id'=>$order_id))->setField('order_status',$status);
    }
    /*
     * 检查抢购商品活动状态
     */
    private function check_cart_order_quota($cart_goods,$uid){
    	$activity = D ( 'favourable_activity' );
    	$cart = D('cart');
    	foreach($cart_goods as $goods){
    		if($goods['is_quota']>0){
    			$favourable = $activity->favourable_info($goods['is_quota']);
    			 
    			if (empty($favourable)) {
    				returnApiError('商品'.$goods['goods_name'].'所在的活动'.$favourable['act_name'].'不存在');
    			}
    			/* 判断活动类型 */
    			if ($favourable ['act_type'] <> 3) {
    				returnApiError('商品'.$goods['goods_name'].'与当前活动类型不匹配！');
    			}
    			
    			/* 判断活动日期是否有效 */
    			$time = gmtime();
    			if ($time < $favourable['_start_time'] || $time > $favourable['_end_time']) {
    				returnApiError('商品'.$goods['goods_name'].'所在的活动'.$favourable['act_name'].'未开始或已结束');
    			}
    			
    			/* 判断用户能否享受该优惠 */
    			if (! $cart->favourable_available ( $favourable, $uid )) {
    				returnApiError ( '活动商品'.$goods['goods_name'].'您无法享受该优惠' );
    			}
    			
    			/* 检查是否选择了产品 */
//     			if (empty ( $goods_id )) {
//     				returnApiError ( '请选择限购商品' );
//     			}
    			
    			/* 检查产品是否有效 */
    			$quota_goods = array ();
    			foreach ( $favourable ['quota'] as $item ) {
    				if ($item ['id'] == $goods['goods_id']) {
    					$quota_goods = $item;
    					break;
    				}
    			}
    			
    			if (empty ( $quota_goods )) {
    				returnApiError ( '活动商品'.$goods['goods_name'].'已过期，请重新购买');
    			}
    			
    			if($quota_goods['price']!=$goods['goods_price']){
    				returnApiError ( '活动商品'.$goods['goods_name'].'已过期，请重新购买');
    			}
    		}
    	}
    }

    public function write_log($message,$filename){
        $log = new Log();
        $destination = C('LOG_PATH').date('y_m_d').'_'.$filename.'.log';

        $log->write($message,'DEBUG','',$destination);
    }


    /**
     * 自动分派订单
     * poptser
     * @param null $order_id
     * @param null $order_info
     * @return bool
     */
    public function auto_dispatch_order($order_id=null, $order_info =null){
        if(!empty($order_id)){
            $order_area = M("order_info")->where(array("order_id"=>$order_id,"shipping_id"=>3))->getField("wdr_id");
            if(empty($order_area)){
                return false;   //未找到此订单/此订单不是配送单
            }
            $order_info['order_id'] = $order_id;
            $order_info['wdr_id'] = $order_area;
        }

        $company_list = M("distribution_company_area")->where(array("area_id"=>$order_info['wdr_id']))
            ->order('id desc')->select();
        //获取此区域所有配送商
        if(empty($company_list)){
            return false;   //无关联配送商，不处理
        }
        //查询今日本区域订单
        $order_num = M("order_info")->where("order_status !=2 and pay_status in (2,3) and shipping_id =3 and wdr_id = {$order_info['wdr_id']}")->count();
        $order_now = $order_num%10;
        $dis_list = array();
        $start_num = 0;
        $dis_company_id = 0;
        foreach ($company_list as $value){
            unset($one_array);
            if($value['order_ratio']==10){
                //此区域全部订单分配到此配送商
                $dis_company_id = $value['company_id'];
                break;
            }else{
                for ($i=0;$i<$value['order_ratio'];$i++){
                    $one_array[] = $i+$start_num;
                }
                $start_num = $i;
                $one_data['id'] = $value['company_id'];
                $one_data['data'] = $one_array;
                $dis_list[] = $one_data;
            }
        }
        //dump($order_now);
        //dump($dis_list);
        if(empty($dis_company_id)){
            foreach ($dis_list as $key=>$value){
                if(in_array($order_now,$value['data'])){
                    $dis_company_id = $value['id'];
                    break;
                }
            }
        }
        if(!empty($dis_company_id)){
            if($order_info['shipping_id']==3&&$dis_company_id==4){
                $this->update_address_gk($order_info);
            }
            M("order_info")->where(array("order_id"=>$order_info['order_id']))
                ->setField('distribution_company_id',$dis_company_id);
            return true;
        }
    }

    private function get_shopping_bag_by_id($shopping_bag,$user_id,$wid){
        $bag_info = array();
        $bag_goods_list = array();
        $bag_total_price = 0;
        $bag_out_stock_goods_list = array();
        if(!empty($shopping_bag)){
            $shopping_bag = str_replace('&quot;','"',$shopping_bag);
            $shopping_bag = json_decode($shopping_bag,true);

            $bag_num_list = array();
            $goods_id_list = array();
            foreach($shopping_bag as $key=>$val){
                if(!empty($val['goods_id']) && !empty($val['goods_number'])){
                    $bag_num_list[$val['goods_id']] = $val['goods_number'];
                    $goods_id_list[] = $val['goods_id'];
                }
            }

            $map = array('goods_id'=>array('in',$goods_id_list));
            $goods_list = M('goods_wid_'.$wid)->where($map)->select();
            foreach ($goods_list as $key=>$goods_info){
                if(!empty($goods_info) && $goods_info['practical_num']>0){
                    $res = array();
                    $res['user_id'] = $user_id;
                    $res['goods_id'] = $goods_info['goods_id'];
                    $res['goods_name'] = $goods_info['goods_name'];
                    $res['goods_sn'] = $goods_info['goods_sn'];
                    $res['product_id'] = 0;
                    $res['goods_number'] = $bag_num_list[$goods_info['goods_id']];
                    $res['market_price'] = $goods_info['shop_price'];
                    $res['goods_price'] = D('goods')->get_vip_price($goods_info['goods_id'], $user_id);
                    $res['goods_discount'] = 0;
                    $res['goods_attr'] = "";
                    $res['is_real'] = 1;
                    $res['extension_code'] = "";
                    $res['parent_id'] = 0;
                    $res['is_gift'] = 0;
                    $res['is_quota'] = 0;
                    $res['is_presell'] = 0;
                    $res['giving'] = 0;
                    $res['rec_type'] = 0;
                    $res['is_shipping'] = 0;
                    $res['can_handsel'] = 0;
                    $res['goods_attr_id'] = "";
                    $res['act_id'] = 0;
                    $res['expiration_date'] = 0;
                    $res['goods_discount'] = 0;
                    $res['is_cashier'] = 0;
                    $res['cashier_id'] = "";
                    $res['use_bonus'] = 0;

                    $bag_total_price+=$res['goods_price']*$res['goods_number'];

                    $bag_goods_list[] = $res;
                }else{
                    $bag_out_stock_goods_list[] = $goods_info;
                }
            }
        }

        $bag_info['goods_list'] = $bag_goods_list;
        $bag_info['total_price'] = round($bag_total_price,2);
        $bag_info['out_stock_goods_list'] = $bag_out_stock_goods_list;

        return $bag_info;
    }

    private function get_shopping_bag($user_id,$wid){
        $bag_list = array();
        $shopping_bag_config = C('shopping_bag_config');
        if($shopping_bag_config['status']==1 && !empty($shopping_bag_config['goods_id'])){
            $map = array('goods_id'=>array('in',$shopping_bag_config['goods_id']));
            $goods_list = M('goods_wid_'.$wid)->where($map)->select();
            foreach ($goods_list as $key=>$goods_info){
            if(!empty($goods_info) && $goods_info['practical_num']>0){
                $res = array();
                $res['goods_id'] = $goods_info['goods_id'];
                $res['goods_name'] = $goods_info['goods_name'];
                $res['goods_sn'] = $goods_info['goods_sn'];
                $res['goods_number'] = $goods_info['practical_num'];
                $res['goods_price'] = D('goods')->get_vip_price($goods_info['goods_id'], $user_id);
                $bag_list[] = $res;
            }
        }
    }

        return $bag_list;
    }

    private function calculate_order_shopping_bag($order,$shopping_bag_total_fee){
        if($shopping_bag_total_fee>0){
            $order['goods_amount'] = round($order['goods_amount']+$shopping_bag_total_fee,2);
            $order['order_amount'] = round($order['order_amount']+$shopping_bag_total_fee,2);
        }
        return $order;
    }


    /**
     * 检查订单是否有38活动的商品
     * @author yangzhic
     * @param $goods_list
     * @param $uid
     * @return bool
     */
    private function check_women_day_activity($goods_list,$uid){
        $flag = false;
        $config = C('women_day_ad');

        $current_time = gmtime();
        $begin_time = local_strtotime('2018-03-06');
        $end_time = local_strtotime('2018-03-08');

        $activity_goods = array();
        if($config['status']==1 && ($current_time>=$begin_time && $current_time<=$end_time)){
            $goods_id_list = $config['goods_id'];
            foreach($goods_list as $goods){
                if(in_array($goods['goods_id'],$goods_id_list)){
                    $flag = true;
                    $activity_goods[] = $goods['goods_name'];
                    break;
                }
            }
        }

        if($flag){
            S('women_day_activity_'.$uid,1);
        }else{
            $data = S('women_day_activity_'.$uid);
            if(!empty($data)){
                S('women_day_activity_'.$uid,null);
            }
        }

        $res  = array('had_activity_goods'=>$flag,'goods_list'=>$activity_goods);

        return $res;
    }
}    